<template>
    <div>
        <el-form ref="form" :model="form" label-width="80px">
            <el-form-item label="用户名">
                <el-input v-model="form.loginid"></el-input>
            </el-form-item>
            <el-form-item label="密码">
                <el-input v-model="form.password"></el-input>
            </el-form-item>
            <el-form-item label="头像">
                <el-upload v-model="form.photoPath"
                           name="file"
                           class="avatar-uploader"
                           action="http://localhost:9999/user/upload"
                           :show-file-list="false"
                           :on-success="handleAvatarSuccess"
                           :before-upload="beforeAvatarUpload">
                    <img v-if="imageUrl" :src="imageUrl" class="avatar">
                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="onSubmit">立即创建</el-button>
                <el-button>取消</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>
<script>

export default {
    data() {
        return {
            form: {
                loginid: '',
                password:''
            },
            imageUrl: ''
        }
    },
    methods: {
        onSubmit() {
            console.log('submit!');
            //发送异步请求
            this.$axios.post(`user/add`,this.form).then(r=>{
                if(r.data=="ok"){
                    alert("添加成功")``
                }else {
                    alert("添加失败")
                }
            })
        },
        //文件上传之后
        handleAvatarSuccess(res, file) {
            this.imageUrl =res
            this.form.photoPath=this.imageUrl
        },
        //文件上传之前
        beforeAvatarUpload(file) {
            //判断要上传的文件类型是否是图片
            const isJPG = file.type === 'image/jpeg';
            //判断要上传的文件大小是否超过2mb
            const isLt2M = file.size / 1024 / 1024 < 2;

            if (!isJPG) {
                this.$message.error('上传头像图片只能是 JPG 格式!');
            }
            if (!isLt2M) {
                this.$message.error('上传头像图片大小不能超过 2MB!');
            }
            return isJPG && isLt2M;
        }
    }
}
</script>
<style>
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}
.avatar-uploader .el-upload:hover {
    border-color: #409EFF;
}
.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
}
.avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>
